package cn.dyw.cloudmusic.thread;

import cn.dyw.cloudmusic.http.CloudMusicHttpRequest;
import cn.dyw.cloudmusic.http.CommentSaveHandleProxy;
import cn.dyw.cloudmusic.http.InitMusicParams;
import cn.dyw.cloudmusic.http.SaveHandle;
import cn.dyw.cloudmusic.http.model.CommentParams;
import lombok.extern.log4j.Log4j;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: dyw770
 * @Date: 2019/1/11 22:38
 * @Description: 处理评论的线程
 */
@Log4j
public class CommentThreadRunnable implements Runnable {

    private String id;

    private InitMusicParams initMusicParams;

    private CommentSaveHandleProxy commentSaveHandleProxy;

    private boolean thread;

    private ThreadPoolExecutor threadPoolExecutor;

    private CloudMusicHttpRequest cloudMusicHttpRequest;

    public CommentThreadRunnable(String id, SaveHandle commentSaveHandle, CloudMusicHttpRequest cloudMusicHttpRequest) {
        this(id, 0, commentSaveHandle, null, cloudMusicHttpRequest);
    }

    public CommentThreadRunnable(String id, int offset,
                                 SaveHandle commentSaveHandle, CloudMusicHttpRequest cloudMusicHttpRequest) {
        this(id, offset, commentSaveHandle, null, cloudMusicHttpRequest);
    }

    public CommentThreadRunnable(String id, int offset, SaveHandle commentSaveHandle,
                                 ThreadPoolExecutor threadPoolExecutor, CloudMusicHttpRequest cloudMusicHttpRequest) {
        this.id = id;
        this.thread = false;
        CommentParams p = new CommentParams(id);
        p.setOffset(offset);
        this.initMusicParams = new InitMusicParams(p);
        this.commentSaveHandleProxy = new CommentSaveHandleProxy(commentSaveHandle);
        this.threadPoolExecutor = threadPoolExecutor;
        this.cloudMusicHttpRequest = cloudMusicHttpRequest;
    }

    @Override
    public void run() {
        if (this.thread) {
            moreThreadCrawl();
        } else {
            singleThreadCrawl();
        }
    }

    /**
     * 单线程抓取
     */
    private void singleThreadCrawl() {
        while (commentSaveHandleProxy.isMore()) {
            cloudMusicHttpRequest.startCall(commentSaveHandleProxy, initMusicParams);
            ((CommentParams) initMusicParams.getParams()).next();
        }
    }

    /**
     * 多线程抓取
     * TODO 未完成
     */
    private void moreThreadCrawl() {
    }
}
